package com.buss.admin.service.impl;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.buss.admin.entity.AdminEntity;
import com.buss.admin.entity.AuthFunctionEntity;
import com.buss.admin.service.IAdminEntityService;
import com.buss.admin.service.IAuthFunctionService;

public class AdminUserLoginRealm extends AuthorizingRealm {

	@Autowired
	private IAdminEntityService adminEntityServiceImpl;

	@Autowired
	private IAuthFunctionService functionService;

	/**
	 * 授权方法
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		AdminEntity user = (AdminEntity) principals.getPrimaryPrincipal();

		List<AuthFunctionEntity> list = null;

		// 如果是超级管理员，拥有超级权限
		if (user.getUsername().equals("admin")) {
			list = functionService.getList(AuthFunctionEntity.class);
		}
		// 添加权限信息
		for (AuthFunctionEntity function : list) {
			info.addStringPermission(function.getCode());
		}
		return info;
	}

	/**
	 * 认证方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		// 从令牌中获得用户名
		String username = upToken.getUsername();

		// 根据用户名查询
		List<AdminEntity> list = adminEntityServiceImpl.findByProperty(AdminEntity.class, "username", username);
		AdminEntity adminEntity = null;
		if (list != null && list.size() > 0) {
			adminEntity = list.get(0);

		}

		if (adminEntity == null) {
			return null;
		} else {
			// 用户名存在
			// 获得数据库中存储的密码
			String password = adminEntity.getPassword();

			// 创建简单认证信息对象
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(adminEntity, password,
					this.getClass().getSimpleName());
			// 返回给安全管理器，由安全管理器负责比对数据库中查询出的密码和页面提交的密码
			return info;

		}

	}

}
